//
//  COSendViewController.swift
//  KOLHub
//
//  Created by Ruthless on 2023/7/27.
//

import UIKit

class COSendViewController: COBaseViewController {

    // MARK: - Property
    var name: String = ""
    var userAvatar = ""
    var userName = "" {
        didSet {
            self.title = userName
        }
    }
    var userId: String = "" {
        didSet {
            let text = UserDefaults.standard.string(forKey: "chatAllUser") ?? ""
            var array = text.components(separatedBy: "---")
            if array.contains(userId) {
                return
            }
            
            array.append(userId)
            let news = array.joined(separator: "---")
            UserDefaults.standard.set(news, forKey: "chatAllUser")
            UserDefaults.standard.set(userAvatar, forKey: "userAvatar---\(userId)")
            UserDefaults.standard.set(userName, forKey: "userName---\(userId)")
            UserDefaults.standard.synchronize()
        }
    }
    var contents: [Any] = []
    
    var saveContents: [COSendMessageModel] = [] {
        didSet {
            let array = saveContents.map { item in
                item.content
            }
            
            if let data = try? NSKeyedArchiver.archivedData(withRootObject: array, requiringSecureCoding: false) {
                UserDefaults.standard.set(data, forKey: "chat-\(userId)")
                UserDefaults.standard.synchronize()
            }
        }
    }
    // MARK: - life cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        if let data = UserDefaults.standard.object(forKey: "chat-\(userId)") as? Data {
            if let contents = try? NSKeyedUnarchiver.unarchivedObject(ofClass: NSArray.self, from: data) as? [String] {
                
                for item in contents {
                    let model = COSendMessageModel()
                    model.avatar = COUserManager.userInfo?.sculpture ?? ""
                    model.content = item
                    self.contents.append(model)
                    self.contents.append("")
                }

                tableView.reloadData()
            }
        }
    }
    
    // MARK: - UI
    override func configUI() {
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: tipButton)

        view.backgroundColor = bgColor
        view.addSubview(tableView)
        view.addSubview(lineView)
        view.addSubview(textField)
        view.addSubview(sendButton)
        
        tableView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview().offset(0)
            make.bottom.equalTo(lineView.snp.top).offset(0)
        }
        
        lineView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().offset(0)
            make.bottom.equalTo(textField.snp.top).offset(-4)
            make.height.equalTo(1)
        }
        
        textField.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalTo(sendButton.snp.left).offset(-16)
            make.bottom.equalToSuperview().offset(-bottomSafeHeight - 10)
            make.height.equalTo(40)
        }
        
        sendButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-20)
            make.centerY.equalTo(textField)
        }
        
        sendButton.setContentHuggingPriority(.required, for: .horizontal)
        sendButton.setContentCompressionResistancePriority(.required, for: .horizontal)
    }
    
    // MARK: - lazy load
    private lazy var tableView: UITableView = {
        let tableV = UITableView()
        tableV.delegate = self
        tableV.dataSource = self
        tableV.register(cellWithClass: CORightMessageCell.self)
        tableV.register(cellWithClass: COEmptyCell.self)
        tableV.backgroundColor = bgColor
        return tableV
    }()
    
    private lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = .rgba(255, 255, 255, 0.1)
        return view
    }()
    
    private lazy var textField: UITextField = {
        let tf = UITextField()
        tf.leftViewMode = .always
        tf.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 40))
        tf.rightViewMode = .always
        tf.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 40))
        tf.font = .bold(13)
        tf.textColor = .white
        tf.textAlignment = .center
        tf.attributedPlaceholder = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.text("Say hi~")?.font(.bold(13)).textColor(.rgba(255, 255, 255, 0.5))
        })
        tf.backgroundColor = .rgba(255, 255, 255, 0.2)
        tf.layer.masksToBounds = true
        tf.layer.cornerRadius = 20
        return tf
    }()
    
    private lazy var sendButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "编组 25"), for: .normal)
        btn.addTarget(self, action: #selector(sendMessage), for: .touchUpInside)
        return btn
    }()
    
    private lazy var tipButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "编组 23"), for: .normal)
        btn.addTarget(self, action: #selector(showTip), for: .touchUpInside)
        return btn
    }()
}

extension COSendViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if let _ = contents[indexPath.row] as? COSendMessageModel {
            
            return UITableView.automaticDimension
        }
        
        return 20
    }
}

extension COSendViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return contents.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let model = contents[indexPath.row] as? COSendMessageModel {
            let cell = tableView.dequeueReusableCell(withClass: CORightMessageCell.self, for: indexPath)
            cell.model = model
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withClass: COEmptyCell.self, for: indexPath)
        
        return cell
        
    }
}

extension COSendViewController {
    @objc
    private func sendMessage() {
        self.view.endEditing(true)
        guard let text = textField.text, !text.isEmpty else {
            return
        }
        
        let model = COSendMessageModel()
        model.avatar = COUserManager.userInfo?.sculpture ?? ""
        model.content = text
        contents.append(model)
        contents.append("")
        textField.text = ""
        tableView.reloadData()
        
        UserDefaults.standard.set(Date(), forKey: "chatTime-\(userId)")
        UserDefaults.standard.synchronize()
        saveContents = contents.filter({ item in
            if let _ = item as? COSendMessageModel {
                return true
            }
            
            return false
        }) as? [COSendMessageModel] ?? [];
    }
}
